var searchURL = './includes/content/steamid.php';
var ajaxLoaderImageURL = './images/default/ajax-loader.gif';
var loaderImageURL = './images/loading.gif'; 
var fullProfileURL = './app/steamprofile.php?full=1&id=';
var fullProfileSearchURL = './app/steamprofile.php?search=1&full=1&id=';
var fullSearchURL = 'http://www.lukerobi.com/app/steamprofile.php?search=1&full=1&fs=1&id=';
var payPalFormURL = './includes/content/paypal_form.php';
var anonymousDonorName = 'Anonymous Donor'; 
var anonymousDonorSteamID = 'STEAM_0:0:00000';
var searchPageNum = 0;

/**
 *  Function triggered by selection an option, it then hides/shows the correct 
 *  sections based upon that selection.
 * */
function optionSelect() {
    // disable option selector?
    if ($('#PlayerSelect').attr('disabled') != false) {
        $('#PlayerSelect').attr('disabled', true);
    }
    
    // remove welcome message?
    if (document.getElementById('welcomeMessage') != null) {
        $('#disableMe').attr('disabled', 'disabled');
        $('#welcomeMessage').hide('slow', function() {
            $(this).remove(); 
            optionSelect();
        });
        return;        
    }

    // hide continue button if visible
    if ($('#ContinuePayPal').is(':visible')) {
        $('#ContinuePayPal').hide('slow', function() {
            optionSelect();    
        });
        return;   
    }

    // is the selection equal to 'anonymous' ?
    if ($('#PlayerSelect').val() == 'anonymous') {                        
        
        // hide the search $ search results paged if we have loaded them.
        if ($('#Search').is(':visible') && ($('#Search').html() != '')) {
            $('#SearchOutput').hide('slow', function() {
                $('#Search').hide('slow', function() {
                    optionSelect();
                });                 
            });           
            return;    
        }

        // hide the player profile
        if ($('#playerProfileDiv').is(':visible')) {
            $('#playerProfileDiv').hide('slow', function() {
                optionSelect();
            });
            return;    
        }
        
        // hide the steamid input box
        if ($('#steamid').is(':visible')) {
            $('#steamidLabel').hide('slow'); 
            $('#steamid').hide('slow', function() {
                optionSelect();
            });               
            return;    
        }

        // show anonymous message
        if (!($('#anonymousMessage').is(':visible'))) {
            $('#anonymousMessage').show('slow', function() {
                optionSelect();
            });               
            return;    
        }        
        
        // show the continue button and enable the option box again
        if (!($('#ContinuePayPal').is(':visible'))) {
            $('#ContinuePayPal').show('slow', function() {
                if ($('#PlayerSelect').attr('disabled')) {
                    $('#PlayerSelect').attr('disabled', false);
                }
            });   
        }
         
    }
    
    // option select; steam id search
    else if ($('#PlayerSelect').val() == 'not_listed') {                        
        
        // hide anonymous message
        if ($('#anonymousMessage').is(':visible')) {
            $('#anonymousMessage').hide('slow', function() {
                optionSelect();
            });               
            return;    
        } 

        // hide the player profile
        if ($('#playerProfileDiv').is(':visible')) {
            $('#playerProfileDiv').hide('slow', function() {
                optionSelect();
            });
            return;    
        }
        
        // hide the steamid input box
        if ($('#steamid').is(':visible')) {
            $('#steamidLabel').hide('slow'); 
            $('#steamid').hide('slow', function() {
                optionSelect();
            });               
            return;    
        }

        // load the search page if we have not, and then show it.  After, enable the option box again
        if ($('#Search').html() == '') {
            $('#Search').html('<p><img class="loadingImage" src="' + ajaxLoaderImageURL + '" alt="loading" /></p>');
            $('#Search').load(searchURL, function() {
                if (!($('#Search').is(':visible'))) {
                    $('#Search').show('slow', function() {
                        $('#SearchOutput').show('slow', function() {
                            if ($('#PlayerSelect').attr('disabled')) {
                                $('#PlayerSelect').attr('disabled', false);
                                if (!($('#SearchOutputError').is(':visible')) && ($('#searchProfile').find('p').length != 1)) {
                                    $('#searchDeep').show('slow');
                                }
                            }                          
                        });    
                    });           
                }              
            });
            return;               
        }  
        
        // show the search page (loaded already). After, enable the option box again 
        if (!($('#Search').is(':visible'))) {
            $('#Search').show('slow', function() {
                $('#SearchOutput').show('slow', function() {
                    if ($('#PlayerSelect').attr('disabled')) {
                        $('#PlayerSelect').attr('disabled', false);
                        $('#searchDeep').show('slow');
                    }                  
                });           
            });
        }    
    }
    
    // player name selected from option drop down
    else {
        
        // fill in the steamid to the input box
        if ($('#steamid').val() != $('#PlayerSelect').val()) {
            if ($('#PlayerSelect').val().substring(0, 7) == 'STEAM_0') { 
                $('#steamid').val($('#PlayerSelect').val());
            }
            else {
                $('#steamid').val('Loading..');
            }    
        }
        
        // hide anonymous message
        if ($('#anonymousMessage').is(':visible')) {
            $('#anonymousMessage').hide('slow', function() {
                optionSelect();
            });               
            return;    
        } 

        // hide the search
        if ($('#Search').is(':visible') && ($('#Search').html() != '')) {
            $('#SearchOutput').hide('slow', function() {
                $('#Search').hide('slow', function() {
                    optionSelect();
                });                 
            });           
            return;    
        }

        // show the player profile
        $('#playerProfileDiv').show('slow', function() {
            $(this).find('.steamprofile').html('<img class="loadingImage" src="' + loaderImageURL + '" alt="loading" />Loading...');
            $(this).find('.steamprofile').load(fullProfileURL + $('#PlayerSelect').val(), function() {                    
                $('#steamid').val($('#profileSteamID').attr('title'));
                $('#playerProfileDiv').find('.friendlyname').textfill({ maxFontPixels: 14 });
                $('#playerProfileDiv').find('.friendlyname').width('auto'); 

                // show the steamid input box
                if (!($('#steamid').is(':visible'))) {
                    $('#steamidLabel').show('slow');
                    $('#steamid').show('slow');   
                }
                
                // update steamid input box
                if ($('#steamid').val().substring(0, 7) != 'STEAM_0') {
                    $('#steamid').val($('#profileSteamID').attr('title'));   
                }
                
                // show the continue button, and unlock the option box
                if (!($('#ContinuePayPal').is(':visible'))) {
                    $('#ContinuePayPal').show('slow');  
                } 
                
                // enable the selector
                if ($('#PlayerSelect').attr('disabled')) {
                    $('#PlayerSelect').attr('disabled', false);
                }                  
            });
        });                
    }
}

/**
 *  Function called when a search is executed from the 'Steam ID Search'
 * */
function lookupSteamID() {
    // show the output area
    if (!($('#SearchOutput').is(':visible'))) {
        $('#SearchOutput').show('slow', function() {
            lookupSteamID();
        });
        
        // return false to stop form from submitting
        return false;                
    }

    // search if the query is not the same as last time
    if ($('#SteamIDSearch').val() != $('#LastSearch').val()) {
        
        // show the continue box if possible
        if ($('#ContinuePayPal').is(':visible')) {
            $('#ContinuePayPal').hide('slow', function() {
                lookupSteamID();    
            });
            // return false to stop form from submitting
            return false;  
        }
        
        window.searchPageNum = 0;
         
        $('#searchProfile').html('<img class="loadingImage" src="' + loaderImageURL + '" alt="loading" />Searching...');
        $('#searchProfile').load(fullProfileSearchURL + $('#SteamIDSearch').val(), function() {
            $('#LastSearch').val($('#SteamIDSearch').val());
            
            // make the changes
            if ($(this).find('.steamprofile')[0] != null) {
                $(this).find('.steamprofile')[0].title = $(this).find('.avatar')[0].title;
                $(this).find('.friendlyname').textfill({ maxFontPixels: 14 });
                $(this).find('.friendlyname').width('auto');
            }
            
            $(this).find('.steamprofile').each(function() {
                var profileId = $('#profileSteamID').attr('title');
                var profileName = $(this).find('.avatar').attr('title');            
                $(this).find('a').each(function() {
                    $(this).attr('href', "javascript:steamSearchProfile('" + profileId + "', '" + profileName + "');");
                });     
            });
            
            // no results?
            if ($(this).text() == '') {
                searchDeep();                  
            }
            $('#searchDeep').show('slow');                
        });        
    }
    // return false to stop form from submitting
    return false;
}

/**
 *  Function triggered by clicking the 'Continue' button.  This function hides 
 *  and disables previous forms in order to move to checkout.
 * */
function continuePayPal() {    
    // disable all forms and hide the continue button
    if ($('#ContinuePayPal').is(':visible')) {
        $('#PlayerSelect').attr('disabled', 'disabled');
        
        try {
            $('#SteamIDSearch').attr('disabled', 'disabled');
            $('#SearchButton').attr('disabled', 'disabled');
        }
        
        catch (error) {}
        
        $('#ContinuePayPal').hide('slow', function() {
            continuePayPal();
        });
        return;    
    }
    
    // hide the search area
    if ($('#Search').is(':visible') && ($('#Search').html() != '')) {
        $('#SearchOutput').hide('slow', function() {
            $('#Search').hide('slow', function() {
                continuePayPal();
            });                 
        });           
        return;    
    }        

    // hide the player profile
    if ($('#playerProfileDiv').is(':visible')) {
        $('#playerProfileDiv').hide('slow', function() {
            continuePayPal();
        });
        return;    
    }

    // hide the steamid input box
    if ($('#steamid').is(':visible')) {
        $('#steamidLabel').hide('slow'); 
        $('#steamid').hide('slow', function() {
            continuePayPal();
        });               
        return;    
    }
    
    // hide the selection dropdown box
    $('#PlayerSelectLabel').hide('slow');    
    $('#PlayerSelect').hide('slow', function() {
        $('#PayPalFormContainer').show('slow');
        $('#PayPalFormContainer').html('<p><img class="loadingImage" src="' + ajaxLoaderImageURL + '" alt="loading" /></p>');
        $('#PayPalFormContainer').load(payPalFormURL, function() {
            
            // get info from anonymous
            if ($('#PlayerSelect').val() == 'anonymous') {
                $('#ppSteamid').val(anonymousDonorSteamID);
                $('#playerName').val(anonymousDonorName);
            }
            
            // get info from search
            else if ($('#PlayerSelect').val() == 'not_listed') {
                $('#ppSteamid').val($('#LastSearch').val());
                $('#playerName').val($('#SearchOutput').find('.steamprofile').find('.avatar').attr('title'));            
            }
            
            // get info from player profile
            else {
                $('#ppSteamid').val($('#steamid').val());
                $('#playerName').val($('#playerProfileDiv').find('.steamprofile').find('.avatar').attr('title'));                
            }      
        });    
    });   
}

/**
 *  Loads the search results provided by the steam community, then change the href links
 * */
function searchDeep() {
    $('#searchProfile').html('<p><img class="loadingImage" src="' + ajaxLoaderImageURL + '" alt="loading" /></p>');
    window.searchPageNum += 1;
    $('#searchProfile').load((fullSearchURL + encodeURIComponent($('#LastSearch').val()) + '&p=' + searchPageNum), function() {        
        $(this).find('.searchResultItem').each(function() {
            var profileId = $(this).find('.searchInfo').attr('title');
            var profileName = $(this).find('.searchInfo').text();            
            $(this).find('a').each(function() {
                $(this).attr('href', "javascript:steamSearchProfile('" + profileId + "', '" + profileName + "');");
            });     
        });
    });  
}

function steamSearchProfile(playerId, playerName) {               
    if ($('#PlayerSelect').find('optgroup').length == 3) {
        $('#PlayerSelect').append('<option disabled="disabled"></option><optgroup label="Search Results"><option value="' + playerId + '">' + playerName + '</option></optgroup>');
    }
    
    else {
        $('#PlayerSelect').find('optgroup:eq(3)').append('<option value="' + playerId + '">' + playerName + '</option>');    
    }

    $('#PlayerSelect').val(playerId);
    optionSelect();
}

/**
 *  Called on document load, it hides some sections by default.
 * */
$(document).ready(function() {
    $('#SearchOutput').hide();
    $('#PayPalFormContainer').hide();
    $('#ContinuePayPal').hide();
    $('#Search').hide();
    $('#anonymousMessage').hide();
    $('#playerProfileDiv').hide();
    $('#searchDeep').hide();
});